<template>
  <div>
    <el-form :inline="true" :model="orderForm" ref="orderForm">
      <div class="pc-page-header">
        <el-form-item prop="orderNo">
          <el-input v-model="orderForm.orderNo" clearable class="pc-input3-col5" placeholder="输入订单号"></el-input>
        </el-form-item>
        <el-form-item prop="status">
          <el-select v-model="orderForm.status" collapse-tags multiple placeholder="选择订单状态" class="pc-input3-col5">
            <el-option v-for="item in statusOption" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="instoreDate">
          <el-date-picker class="block"
                          v-model="orderForm.instoreDate"
                          type="daterange"
                          range-separator="-"
                          start-placeholder="选择下单开始日期"
                          end-placeholder="选择下单结束日期"
                          value-format="yyyy-MM-dd"
                          @change="pickDate">
          </el-date-picker>
        </el-form-item>
        <el-form-item prop="ownerName" v-show="isshowMore">
          <el-input v-model="orderForm.ownerName" clearable class="pc-input3-col5"
                    placeholder="输入货主企业"></el-input>
        </el-form-item>
        <el-form-item prop="storageName" v-show="isshowMore">
          <el-input v-model="orderForm.storageName" clearable class="pc-input3-col5"
                    placeholder="输入入库仓库"></el-input>
        </el-form-item>
        <el-form-item label="">
          <el-button type="primary" @click="queryDataFn">搜索</el-button>
          <el-button type="primary" @click="refresh('orderForm', true)">刷新</el-button>
          <el-button  size="small" v-permission="['wms:stockmanager:order:findstore']" type="primary" @click="openAddDialog">找库</el-button>
          <el-button @click="showMore()">{{showMoreText}}</el-button>
        </el-form-item>
      </div>
    </el-form>
    <egrid border
           class="page-list"
           :data="tableData"
           :columns="columns"
           :columns-schema="columnsSchema"
           :columns-props="columnsProps"
           :columns-handler="columnsHandler">
    </egrid>
    <div class="pc-pagination-panel">
      <pc-pagination ref="pcPagination" :url="pageUrl.queryRoleList" :queryData="orderForm" @on-query="queryCallBackFn">
      </pc-pagination>
    </div>
    <pc-dialog :is-show="isShowAddDialog" :title="orderTitle" @on-close="isShowAddDialog = false">
      <find-storage :id="findStoreOrderId" @refreshData="refreshData('orderForm', false)"></find-storage>
    </pc-dialog>
    <pc-dialog :is-show="isShowDetail" title="找库订单详情" @on-close="isShowDetail = false">
      <order-detail :id="findStoreOrderId"></order-detail>
    </pc-dialog>
  </div>
</template>
<script type="text/ecmascript-6">
  import PcPagination from 'components/form/pagination';
  import PcButton from 'components/form/button';
  import PcDialog from 'components/dialog';
  import EgridCellView from 'components/wms/comm/EgridCellView';
  // import LongContentCol from 'components/wms/comm/LongContentColComponent';
  import FindStorage from '@/views/wms/stockmanager/ordermanagement/findStorage';
  import OrderDetail from '@/views/wms/stockmanager/ordermanagement/orderDetail';

  let that;
  // 操作按钮
  var Btn = {
    template:
      `<div style="display:flex; width: 100%;flex-wrap: wrap">
        <el-button v-if="showHandle && hasPermission('wms:stockmanager:order:handle')" type="danger" plain @click="handleOrder(row)">处理订单</el-button>
        <el-button v-if="!showHandle && hasPermission('wms:stockmanager:order:orderdetail')" type="primary" plain @click="viewdetail(row)">详情</el-button>
        <el-button v-if="showHandle && hasPermission('wms:stockmanager:order:cancel')" type="info" plain @click="cancelOrder(row)">取消</el-button>
      </div>`,
    props: ['row'],
    computed: {
      showHandle() {
        return this.row.status === 1;
      }
    },
    methods: {
      handleOrder (val) {
//        console.log('handle order------row: ' + JSON.stringify(val));
        this.$emit('handle-order', val);
      },
      cancelOrder (val) {
//        console.log('candel order!');
        this.$emit('cancel-order', val);
      },
      viewdetail(val) {
//        console.log('view detail------row: ' + JSON.stringify(val));
        this.$emit('order-detail', val);
      }
    }
  };
  export default {
    data () {
      return {
        isshowMore: false,
        isShowAddDialog: false,
        showMoreText: '更多',
        roleType: 0, // 1超级管理员 2云仓 3 货主企业
        orderForm: {
          status: [],
          orderNo: null,
          instoreDate: null,
          ownerName: null,
          storageName: null,
          startDate: null,
          endDate: null
        },
        orderStatus: '',
        tableData: [],
        columns: [
          {
            label: '订单号',
            prop: 'orderNo'
          },
          {
            label: '订单状态',
            prop: 'statusName'
          },
          {
            label: '下单日期',
            prop: 'instoreDate'
          },
          {
            label: '货主企业',
            prop: 'ownerName'
          },
          {
            label: '入库仓库',
            prop: 'storageName'
          },
          {
            label: '操作',
            minWidth: 202,
            fixed: 'right',
            component: Btn, // 'el-button'
            listeners: {
              'handle-order' (data) {
                that.handleOrder(data);
              },
              'cancel-order' (data) {
                that.cancelOrder(data);
              },
              'order-detail' (data) {
                that.orderDetail(data);
              }
            },
            propsHandler: function ({ row, col, column }) {
              return {row, col, column};
            }
          }
        ],
        columnsSchema: {
          '下单日期': { minWidth: 180 },
          '货主企业': {
            minWidth: 240
            // 定义表格列如何渲染，用showOverflowTooltip: true代替
//            component: LongContentCol // 列内容过长内容展示组件（设置超出部分隐藏，鼠标移上去显示全部）
          },
          '入库仓库': {
            minWidth: 240,
            component: EgridCellView
            // 定义表格列如何渲染, 用showOverflowTooltip: true代替
//            component: LongContentCol // 列内容过长内容展示组件（设置超出部分隐藏，鼠标移上去显示全部）
          }
        },
        // columnsProps 用于定义所有 columns 公共的属性，
        // 这里属性可以参考这里： http://element.eleme.io/#/zh-CN/component/table#table-column-attributes
        columnsProps: {
          height: 40,
          minWidth: 150,
          showOverflowTooltip: true
        },
        statusOption: [{
          value: '1',
          label: '待处理'
        }, {
          value: '2',
          label: '已处理'
        },
        {
          value: '3',
          label: '已取消'
        }],
        emptyText: '',
        currentPage: 1,
        pageUrl: {
          queryRoleList: '/maliwms/instoreOrder/listOrder' // 列表数据接口地址
        },
        orderTitle: '',
        isShowDetail: false,
        findStoreOrderId: null
      };
    },
    components: {
      PcPagination, PcButton, PcDialog, FindStorage, OrderDetail
    },
    created () {
      this.roleType = parseInt(this.$store.getters.getRoleId);
      that = this;
    },
    methods: {
      // 表头样式
      getHeaderStyle({ row, column, rowIndex, columnIndex }) {
        if (rowIndex === 0) {
          return 'background: #f5f5f5; height: 50px';
        } else {
          return '';
        }
      },
      showMore () {
        this.isshowMore = !this.isshowMore;
        if (this.isshowMore) {
          this.showMoreText = '收起';
        } else {
          this.showMoreText = '更多';
        }
      },
      // 请求订单管理列表接口成功回调函数
      queryCallBackFn (res) {
        this.tableData = res.result.list;
//        console.log('data: ' + JSON.stringify(this.tableData));
      },
      // 获取订单管理列表数据
      queryDataFn (isRefresh) {
        this.$refs.pcPagination.queryListWithPageFn(isRefresh);
      },
      // 新增/处理找库订单成功，刷行数据
      refreshData (formName, isRefresh) {
        this.isShowAddDialog = false; // 关闭找库画面
        this.$refs[formName].resetFields();
        this.$refs.pcPagination.queryListWithPageFn(isRefresh);
      },
      // 刷新订单管理列表数据
      refresh (formName, isRefresh) {
        this.$refs[formName].resetFields();
        this.orderForm.startDate = '';
        this.orderForm.endDate = '';
        this.queryDataFn(isRefresh);
      },
      // 取消找库订单
      cancelOrder (val) {
        this.$pcMessageBox.prompt(null, '取消理由', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: null,
          inputErrorMessage: '请输入取消理由',
          inputPlaceholder: '请输入取消理由',
          inputValidator: (val) => {
            if (!val || val === '') {
              return '请输入取消理由';
            }
            if (val.length > 200) {
              return '输入长度不能大于200';
            }
          }
        }).then(({ value }) => {
          this.ajax({
            type: 'POST',
            url: '/maliwms/instoreOrder/cancel',
            data: {id: val.id, cancelReason: value, version: val.version},
            loading: true,
            success: (res) => {
              if (res.code === 200) {
                this.successTip('提交成功');
              } else {
                this.errorTip(res.message);
              }
              this.queryDataFn();
            }
          });
        }).catch(() => {
        });
      },
      // 找库订单详情页面
      orderDetail (val) {
        this.findStoreOrderId = val.id;
        this.isShowAddDialog = false;
        this.isShowDetail = true;
      },
      openAddDialog() {
        this.orderTitle = '找库';
        this.findStoreOrderId = null;
        this.isShowDetail = false;
        this.isShowAddDialog = true;
      },
      hideAddDialog() {
        this.isShowAddDialog = false;
      },
      columnsHandler() {

      },
      handleOrder(val) {
        this.orderTitle = '找库';
        this.findStoreOrderId = val.id;
//        console.log('handleOrder--->： ' + JSON.stringify(val) + ' findStoreOrderId: ' + this.findStoreOrderId);
        this.isShowDetail = false;
        this.isShowAddDialog = true;
      },
      pickDate() {
        if (this.orderForm.instoreDate === null) {
          this.orderForm.startDate = '';
          this.orderForm.endDate = '';
        } else {
          this.orderForm.startDate = this.orderForm.instoreDate[0];
          this.orderForm.endDate = this.orderForm.instoreDate[1];
        }
      },
      // 选择订单状态变化时回调函数
      handleChange(val) {
        let that = this;
        this.orderForm.status = [];
        // 循环取出选择的状态数据，转换成数字
        val.forEach(function (value, index) {
          if (value) {
            that.orderForm.status.push(parseInt(value));
          }
        });
      }
    }
  };
</script>
